import React from 'react'
import {connect} from 'react-redux'
import {List, Badge} from 'antd-mobile'


const Item = List.Item
const Brief = Item.Brief

@connect(
    state => state
)
class Msg extends React.Component {


    getlast(arr) {
        return arr[arr.length - 1]
    }

    render() {
        const chatGroup = {}
        this.props.chat.chatMsg.forEach(v => {
            chatGroup[v.chatid] = chatGroup[v.chatid] || []
            chatGroup[v.chatid].push(v)
        })
        const chatList = Object.values(chatGroup).sort((a, b) => {
            const a_last = this.getlast(a).create_time
            const b_last = this.getlast(b).create_time
            return b_last - a_last
        })
        //所有用户的集合
        const users = this.props.chat.users
        //当前登录用户
        const userid = this.props.user._id



        return (
            <div>

                {chatList.map(v => {
                    const lastItem = this.getlast(v)
                    //聊天对象的id
                    const targetId = lastItem.from === userid ? lastItem.to : lastItem.from
                    //未读消息数量
                    const unread = v.filter(el => !el.read && el.from === targetId).length
                    //存在的问题 niuren1发送一个信息 boss1和boss2 都会显示这个chatList 加一层判断就行了
                    //发送给谁的
                    const to=lastItem.to
                    const from=lastItem.from
                    return userid===to||userid===from?(
                        <div key={lastItem._id} onClick={() => this.props.history.push(`/chat/${targetId}`)}>
                            <List  >
                                <Item
                                    arrow="horizontal"
                                    thumb={require(`../img/${users[targetId].avator}.png`)}
                                    extra={<Badge text={unread}/>}
                                >
                                    {lastItem.content}
                                    <Brief>{users[targetId].name}</Brief>
                                </Item>
                            </List>
                        </div>
                    ):null
                })}


            </div>
        )
    }
}

export default Msg